﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Text;
using System.Collections;
using System.Data;

public partial class menu_uc_left_nav_home : DAO.ESWebUserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Int64 langId = DAO.Connection.DEFAULT_LANGUAGE;
        if (Session["language"] != null)
            Int64.TryParse(Session["language"].ToString(), out langId);
        InitializeUI();
        if (!Page.IsPostBack)
        {
            LoadCountry();
            LoadTransportType(this.LangId);
            LoadCompanyType(this.LangId);
            LoadLinks();
            LoadSpecialOffers();
            LoadNewComanies();
            LoadAppTypes(langId);
            LoadTransportTypes(langId);

            if (Request.QueryString["typeid"] != null && Request.QueryString["typeid"] != "")
            {
                long typeid = 0;
                Dictionary<long, long> vehicle_types = new Dictionary<long, long>();
                vehicle_types.Add(166, 13);
                vehicle_types.Add(164, 14);
                vehicle_types.Add(165, 3);
                vehicle_types.Add(167, 1);
                if (Int64.TryParse(Request.QueryString["typeid"].ToString(), out typeid))
                {
                    if (vehicle_types.ContainsKey(typeid))
                    {
                        LoadVehicleTypes(vehicle_types[typeid]);
                    }
                }
            }

            LoadPlacementTypes(langId);
            LoadSearchCrit();

        }

    }

    private void LoadCompanyType(int lang)
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM dbo.Fn_GetAllUniversalTypes(0, 1000000, 'id', 'asc', 2, " + lang + ") WHERE isActive='true'", conn))
            {
                SqlDataReader dr = cmd.ExecuteReader();
                ddl_CompanyType.Items.Add(new ListItem("", "0"));
                if (lang == DAO.Connection.DEFAULT_LANGUAGE)
                {
                    while (dr.Read())
                    {
                        ddl_CompanyType.Items.Add(new ListItem(dr["name"].ToString(), dr["id"].ToString()));
                    }
                }
                else
                {
                    while (dr.Read())
                    {
                        ddl_CompanyType.Items.Add(new ListItem(dr["name"].ToString(), dr["parent_id"].ToString()));
                    }
                }
                dr.Close();
            }
        }
    }

    private void LoadSearchCrit()
    {
        if (Request.QueryString["typeid"] != null && Request.QueryString["typeid"] != "")
            ddl_type_transport.SelectedValue = Request.QueryString["typeid"];

        if (Request.QueryString["offerid"] != null && Request.QueryString["offerid"] != "")
            ddl_type_offer.SelectedValue = Request.QueryString["offerid"];

        if (Request.QueryString["country"] != null && Request.QueryString["country"] != "")
            ddl_country.SelectedValue = Request.QueryString["country"].ToString();

        if (Request.QueryString["postcode"] != null && Request.QueryString["postcode"] != "")
            tb_postCode.Text = Request.QueryString["postcode"].ToString();

        if (Request.QueryString["vehicle_type"] != null && Request.QueryString["vehicle_type"] != "")
            ddl_vehicleType.SelectedValue = Request.QueryString["vehicle_type"].ToString();

        if (Request.QueryString["placement_type"] != null && Request.QueryString["placement_type"] != "")
            ddl_placementType.SelectedValue = Request.QueryString["placement_type"].ToString();

        if (Request.QueryString["date"] != null && Request.QueryString["date"] != "")
            tb_date.Text = Request.QueryString["date"].ToString();
    }

    private void LoadAppTypes(Int64 langId)
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT * from dbo.Fn_GetTypeByType(@language_id,@type_id,0,30,'id','desc') WHERE isActive = 'true'", conn))
            {
                SqlParameter[] pars = new SqlParameter[2];
                pars[0] = new SqlParameter("language_id", langId);
                pars[1] = new SqlParameter("type_id", 12);

                foreach (SqlParameter s in pars)
                    cmd.Parameters.Add(s);
                SqlDataReader dr = cmd.ExecuteReader();
                ddl_type_offer.Items.Clear();
                ddl_type_offer.Items.Add(new ListItem("", "0"));
                while (dr.Read())
                {
                    if (LangId == DAO.Connection.DEFAULT_LANGUAGE)
                    {
                        ddl_type_offer.Items.Add(new ListItem(dr["name"].ToString(), dr["id"].ToString()));
                    }
                    else
                    {
                        ddl_type_offer.Items.Add(new ListItem(dr["name"].ToString(), dr["parent_id"].ToString()));
                    }
                }
                dr.Close();
            }
        }
    }

    private void LoadTransportTypes(Int64 langId)
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT * from dbo.Fn_GetTypeByType(@language_id,@type_id,0,30,'id','desc') WHERE isActive = 'true'", conn))
            {
                SqlParameter[] pars = new SqlParameter[2];
                pars[0] = new SqlParameter("language_id", langId);
                pars[1] = new SqlParameter("type_id", 9);

                foreach (SqlParameter s in pars)
                    cmd.Parameters.Add(s);
                SqlDataReader dr = cmd.ExecuteReader();
                ddl_type_transport.Items.Clear();
                ddl_type_transport.Items.Add(new ListItem("", "0"));
                while (dr.Read())
                {
                    if (LangId == DAO.Connection.DEFAULT_LANGUAGE)
                    {
                        ddl_type_transport.Items.Add(new ListItem(dr["name"].ToString(), dr["id"].ToString()));
                    }
                    else
                    {
                        ddl_type_transport.Items.Add(new ListItem(dr["name"].ToString(), dr["parent_id"].ToString()));
                    }
                }
                dr.Close();
            }
        }
    }

    private void LoadCountry()
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT id, short, name FROM dbo.Fn_GetAllPlaces(0, 1000000, 'id', 'asc', 2) WHERE isActive='true' Order By name asc", conn))
            {
                SqlDataReader dr = cmd.ExecuteReader();
                ddl_country.Items.Add(new ListItem("", "0"));
                dd_country.Items.Add(new ListItem("", "0"));
                while (dr.Read())
                {
                    ddl_country.Items.Add(new ListItem(dr["name"].ToString() + " - " + dr["short"].ToString(), dr["id"].ToString()));
                    dd_country.Items.Add(new ListItem(dr["name"].ToString() + " - " + dr["short"].ToString(), dr["id"].ToString()));
                }
                dr.Close();
            }
        }
    }

    private void LoadTransportType(int lang)
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM dbo.Fn_GetAllUniversalTypes(0, 1000000, 'id', 'asc', 7, " + lang + ") WHERE isActive='true'", conn))
            {
                SqlDataReader dr = cmd.ExecuteReader();
                ddl_TransportType.Items.Add(new ListItem("", "0"));
                if (lang == DAO.Connection.DEFAULT_LANGUAGE)
                {
                    while (dr.Read())
                    {
                        ddl_TransportType.Items.Add(new ListItem(dr["name"].ToString(), dr["id"].ToString()));
                    }
                }
                else
                {
                    while (dr.Read())
                    {
                        ddl_TransportType.Items.Add(new ListItem(dr["name"].ToString(), dr["parent_id"].ToString()));
                    }
                }
                dr.Close();
            }
        }
    }


    private void LoadVehicleTypes(Int64 typeid)
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT * from dbo.Fn_GetTypeByType(@language_id,@type_id,0,30,'id','desc')", conn))
            {
                SqlParameter[] pars = new SqlParameter[2];
                pars[0] = new SqlParameter("language_id", this.LangId);
                pars[1] = new SqlParameter("type_id", typeid);

                foreach (SqlParameter s in pars)
                    cmd.Parameters.Add(s);
                SqlDataReader dr = cmd.ExecuteReader();
                ddl_vehicleType.Items.Clear();
                ddl_vehicleType.Items.Add(new ListItem("", "0"));
                while (dr.Read())
                {
                    if (LangId == DAO.Connection.DEFAULT_LANGUAGE)
                    {
                        ddl_vehicleType.Items.Add(new ListItem(dr["name"].ToString(), dr["id"].ToString()));
                    }
                    else
                    {
                        ddl_vehicleType.Items.Add(new ListItem(dr["name"].ToString(), dr["parent_id"].ToString()));
                    }
                }
                dr.Close();
            }
        }
    }

    private void LoadPlacementTypes(Int64 langId)
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT * from dbo.Fn_GetTypeByType(@language_id,@type_id,0,30,'id','desc')", conn))
            {
                SqlParameter[] pars = new SqlParameter[2];
                pars[0] = new SqlParameter("language_id", langId);
                pars[1] = new SqlParameter("type_id", 8);

                foreach (SqlParameter s in pars)
                    cmd.Parameters.Add(s);
                SqlDataReader dr = cmd.ExecuteReader();
                ddl_placementType.Items.Clear();
                ddl_placementType.Items.Add(new ListItem("", "0"));
                while (dr.Read())
                {
                    if (LangId == DAO.Connection.DEFAULT_LANGUAGE)
                    {
                        ddl_placementType.Items.Add(new ListItem(dr["name"].ToString(), dr["id"].ToString()));
                    }
                    else
                    {
                        ddl_placementType.Items.Add(new ListItem(dr["name"].ToString(), dr["parent_id"].ToString()));
                    }
                }
                dr.Close();
            }
        }
    }

    protected override void InitializeUI()
    {
        long langId = DAO.Connection.DEFAULT_LANGUAGE;
        if (Session["language"] != null)
            long.TryParse(Session["language"].ToString(), out langId);

        this.LangId = Convert.ToInt32(langId);
    }


    protected void btn_submit_Click1(object sender, EventArgs e)
    {
        string url = "";
        url += "name=" + tbCompany.Text;
        if (ddl_TransportType.SelectedValue != "0")
        {
            url += "&ttype=" + ddl_TransportType.SelectedValue;
        }
        if (ddl_CompanyType.SelectedValue != "0")
        {
            url += "&catid=" + ddl_CompanyType.SelectedValue;
        }
        if (dd_country.SelectedValue != "0")
        {
            url += "&countryid=" + dd_country.SelectedValue;
        }
        Response.Redirect("~/Company.aspx?" + url);
    }
    protected void btn_submit_Click(object sender, EventArgs e)
    {
        StringBuilder url_param = new StringBuilder();
        url_param.Append("?search=true");
        if (ddl_type_transport.SelectedValue != "0")
        {
            url_param.Append("&typeid=" + ddl_type_transport.SelectedValue);
        }
        if (ddl_type_offer.SelectedValue != "0")
        {
            url_param.Append("&offerid=" + ddl_type_offer.SelectedValue);
        }
        if (tb_postCode.Text != "")
        {
            url_param.Append("&postcode=" + tb_postCode.Text);
        }
        if (ddl_vehicleType.SelectedValue != "0")
        {
            url_param.Append("&vehicle_type=" + ddl_vehicleType.SelectedValue);
        }
        if (ddl_placementType.SelectedValue != "0")
        {
            url_param.Append("&placement_type=" + ddl_placementType.SelectedValue);
        }
        if (ddl_country.SelectedValue != "0")
        {
            url_param.Append("&country=" + ddl_country.SelectedValue);
        }
        if (tb_date.Text != "")
        {
            url_param.Append("&date=" + tb_date.Text);
        }

        Response.Redirect("~/application.aspx" + url_param.ToString());
    }

    protected void ddl_type_transport_SelectedIndexChanged(object sender, EventArgs e)
    {
        long typeid = 0;
        Dictionary<long, long> vehicle_types = new Dictionary<long, long>();
        vehicle_types.Add(166, 13);
        vehicle_types.Add(164, 14);
        vehicle_types.Add(165, 3);
        vehicle_types.Add(167, 1);
        if (Int64.TryParse(ddl_type_transport.SelectedValue, out typeid))
        {
            if (vehicle_types.ContainsKey(typeid))
            {
                LoadVehicleTypes(vehicle_types[typeid]);
            }
        }
    }

    private void LoadLinks()
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM dbo.Fn_GetAllLinks(0, 1000000, 'id', 'asc', " + this.LangId + ") WHERE isActive='true'", conn))
            {
                SqlDataReader dr = null;
                dr = cmd.ExecuteReader();
                HyperLink h;
                while (dr.Read())
                {
                    h = new HyperLink();
                    h.NavigateUrl = "HTTP://" + dr["link"].ToString();
                    h.Target = "_blank";
                    h.Text = ">> " + dr["link_text"].ToString();
                    h.CssClass = "accessoriesLink";
                    phLinks.Controls.Add(
                        new LiteralControl("<div style='width:200px'>"));
                    phLinks.Controls.Add(h);
                    phLinks.Controls.Add(
                        new LiteralControl("</div>"));
                }
            }
        }
    }

    private void LoadNewComanies()
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM Fn_GetNewCompanies()", conn))
            {
                try
                {
                    SqlDataReader dr = null;
                    dr = cmd.ExecuteReader();
                    HyperLink h;
                    while (dr.Read())
                    {
                        h = new HyperLink();
                        h.NavigateUrl = "~/CompanyDetails.aspx?cid=" + dr["comp_id"].ToString();
                        h.Target = "_blank";
                        string code = (dr["CountryCode"] != null) ? dr["CountryCode"].ToString() : "N/A";
                        string country_name = (dr["CountryName"] != null) ? dr["CountryName"].ToString() : "N/A";
                        if (dr["CompanyName"] != null && dr["CompanyName"].ToString() != "")
                        {
                            h.Text = ">> " + dr["CompanyName"].ToString();
                            if (dr["CompanyName"].ToString().Length > 15)
                            {
                                h.Text = ">> " + dr["CompanyName"].ToString().Substring(0, 11) + "&nbsp;...";
                            }
                        }
                        h.CssClass = "specOffers";
                        phNewCompanies.Controls.Add(new LiteralControl("<table align='left' width='190px' border='0'>"));
                        phNewCompanies.Controls.Add(new LiteralControl("<tr>"));
                        phNewCompanies.Controls.Add(new LiteralControl("<td width='40px' align='left'>"));
                        phNewCompanies.Controls.Add(new LiteralControl("<img width=\"35px\" src=\"design_img/CompanyLogoDefault.jpg\" style='margin:0;' />"));
                        phNewCompanies.Controls.Add(new LiteralControl("</td>"));
                        phNewCompanies.Controls.Add(new LiteralControl("<td>"));
                        phNewCompanies.Controls.Add(h);
                        if (country_name.Length > 15)
                        {
                            phNewCompanies.Controls.Add(new LiteralControl("<p title='" + country_name + "'><b>" +
                                code + " - " + country_name.Substring(0, 12) + "...</b></p>"));
                        }
                        else
                        {
                            phNewCompanies.Controls.Add(new LiteralControl("<p title='" + country_name + "'><b>"
                                + code + " - " + country_name + "</b></p>"));
                        }
                        phNewCompanies.Controls.Add(new LiteralControl("</td>"));
                        phNewCompanies.Controls.Add(new LiteralControl("</tr>"));
                        phNewCompanies.Controls.Add(new LiteralControl("</table>"));
                    }
                }
                catch (Exception ex) { }
            }
        }
    }


    private void LoadSpecialOffers()
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SP_GetApplications", conn))
            {
                try
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@start", SqlDbType.BigInt).Value = 0;
                    cmd.Parameters.Add("@limit", SqlDbType.BigInt).Value = 5;
                    cmd.Parameters.Add("@sortby", SqlDbType.NVarChar).Value = "ID DESC";
                    SqlDataReader dr = null;
                    dr = cmd.ExecuteReader();
                    HyperLink h;
                    while (dr.Read())
                    {
                        Dictionary<string, ArrayList> LoadLoadingUnloadingData = LoadLoadingUnloadingInfo(Int64.Parse(dr["id"].ToString()));

                        string loading_date = "N/A";
                        ArrayList loading_codes;
                        ArrayList loading_countries;
                        ArrayList unloading_countries;
                        ArrayList loading_dates;
                        ArrayList unloading_codes;
                        ArrayList unloading_dates;
                        DateTime dt;
                        StringBuilder sb = new StringBuilder();

                        //Loading Countries
                        if (LoadLoadingUnloadingData.TryGetValue("loading_codes", out loading_codes) &&
                            LoadLoadingUnloadingData.TryGetValue("loading_countries", out loading_countries))
                        {
                            int count = loading_codes.Count;
                            if (count == 1)
                            {
                                sb.Append("<img width=\"20\" title='" + loading_countries[0].ToString() +
                                    "' height=\"12\" src=\"images/countries/" + loading_codes[0].ToString() + "-t.gif\" /> "
                                    + loading_codes[0].ToString());

                            }
                            else
                            {
                                for (int i = 0; i < count; i++)
                                {
                                    sb.Append("<img width=\"20\" height=\"12\" title='" + loading_countries[i].ToString()
                                        + "' src=\"images/countries/" + loading_codes[i].ToString() + "-t.gif\" />&nbsp;");
                                }
                            }
                        }
                        sb.Append("<span style='font-size:15px'> - </span>");
                        //UnLoading Countries
                        if (LoadLoadingUnloadingData.TryGetValue("unloading_codes", out unloading_codes) &&
                            LoadLoadingUnloadingData.TryGetValue("unloading_countries", out unloading_countries))
                        {
                            int count = unloading_countries.Count;
                            if (count == 1)
                            {
                                sb.Append("<img width=\"20\" title='" + unloading_countries[0].ToString() +
                                    "' height=\"12\" src=\"images/countries/" + unloading_codes[0].ToString() + "-t.gif\" /> "
                                    + unloading_codes[0].ToString());

                            }
                            else
                            {
                                for (int i = 0; i < unloading_countries.Count; i++)
                                {
                                    sb.Append("<img width=\"20\" height=\"12\" title='" + unloading_countries[i].ToString()
                                        + "' src=\"images/countries/" + unloading_codes[i].ToString() + "-t.gif\" />&nbsp;");
                                }
                            }
                        }

                        if (LoadLoadingUnloadingData.TryGetValue("loading_dates", out loading_dates))
                        {
                            for (int i = 0; i < 1; i++)
                            {
                                if (DateTime.TryParse(loading_dates[i].ToString(), out dt))
                                {
                                    loading_date = dt.ToShortDateString() + " ";
                                }
                            }
                        }
                        string unloading_date = "N/A";
                        if (LoadLoadingUnloadingData.TryGetValue("unloading_dates", out unloading_dates))
                        {
                            for (int i = 0; i < 1; i++)
                            {
                                if (DateTime.TryParse(unloading_dates[i].ToString(), out dt))
                                {
                                    unloading_date = dt.ToShortDateString() + " ";
                                }
                            }
                        }

                        h = new HyperLink();
                        h.NavigateUrl = "~/ApplicationDetails.aspx?id=" + dr["id"].ToString();
                        h.Target = "_blank";
                        h.Text = ">> " + sb.ToString();
                        h.CssClass = "accessoriesLink";

                        phSpecOffers.Controls.Add(new LiteralControl("<div style='width:160px;border-top:2px solid #464a4d;'>"));
                        phSpecOffers.Controls.Add(h);
                        phSpecOffers.Controls.Add(new LiteralControl("<br><span style='padding-left:15px' class='accessoriesLink'>" +
                            DAO.TextBaseFactory.loadText("loading", this.LangId) + "&nbsp;&nbsp;&nbsp;&nbsp;" + loading_date + "</span>"));
                        phSpecOffers.Controls.Add(new LiteralControl("<br><span style='padding-left:15px' class='accessoriesLink'>" +
                            DAO.TextBaseFactory.loadText("unloading", this.LangId) + "&nbsp;" + unloading_date + "</span>"));
                        phSpecOffers.Controls.Add(new LiteralControl("</div>"));
                    }
                }
                catch (Exception ex) { }
            }
        }
    }

    #region LoadLoadingUnloadingInfo
    private Dictionary<string, ArrayList> LoadLoadingUnloadingInfo(long app_id)
    {
        Dictionary<string, ArrayList> LoadingUnloadingInfo = new Dictionary<string, ArrayList>();
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM Fn_getLoadingUnloadingByAppId(@app_id)", conn))
            {
                cmd.Parameters.Add("app_id", app_id);
                SqlDataReader dr = cmd.ExecuteReader();
                ArrayList loading_codes = new ArrayList();
                ArrayList loading_countries = new ArrayList();
                ArrayList unloading_countries = new ArrayList();
                ArrayList loading_dates = new ArrayList();
                ArrayList unloading_codes = new ArrayList();
                ArrayList unloading_dates = new ArrayList();
                while (dr.Read())
                {
                    loading_codes.Add(dr["loading_country_code"].ToString());
                    loading_dates.Add(dr["loading_date"].ToString());
                    unloading_codes.Add(dr["unloading_country_code"].ToString());
                    unloading_dates.Add(dr["unloading_date"].ToString());
                    loading_countries.Add(dr["loading_country_name"].ToString());
                    unloading_countries.Add(dr["unloading_country_name"].ToString());

                }
                LoadingUnloadingInfo.Add("loading_codes", loading_codes);
                LoadingUnloadingInfo.Add("loading_dates", loading_dates);
                LoadingUnloadingInfo.Add("unloading_codes", unloading_codes);
                LoadingUnloadingInfo.Add("unloading_dates", unloading_dates);
                LoadingUnloadingInfo.Add("loading_countries", loading_countries);
                LoadingUnloadingInfo.Add("unloading_countries", unloading_countries);

            }
        }
        return LoadingUnloadingInfo;
    }
    #endregion
}